package client.comm.baoding.ui

import android.text.TextUtils
import androidx.lifecycle.Observer
import client.comm.commlib.dialog.SelectAddrDialog
import client.comm.commlib.toast.toast
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.databinding.ActivityAddaddrBinding
import client.comm.baoding.ui.vm.AddAddrViewModel
import client.comm.baoding.api.bean.UserAddress

class AddAddrActivity : BaseMiddleActivity<AddAddrViewModel, ActivityAddaddrBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_addaddr
    }

    override fun initViewModel(): AddAddrViewModel = createViewModel()

    override fun initView() {
        binding?.apply {
            event = this@AddAddrActivity
            vm = viewModel

            if (intent.getBooleanExtra("isEdit", false)) {
                title = "编辑收货地址"
                val bean = intent.getSerializableExtra("bean")
                bean?.let {
                    it as UserAddress.Address
                    viewModel.name.value = it.name
                    viewModel.phone.value = it.phone
                    viewModel.qu.value = "${it.province} ${it.city} ${it.district}"

                    viewModel.detail.value = it.place
                    viewModel.id.value = "${it.address_id}"
                }
            } else
                title = "新增收货地址"

        }
    }

    override fun observerUI() {
        viewModel.call.observe(this, Observer {
            it?.apply {
                if (isSuccess) {
                    toast("操作成功")
                    finish()
                }
            }
        })
    }


    fun selectAddr() {
        val dialog = SelectAddrDialog(this)

        var one = ""
        var two = ""
        var three = ""
        if (!TextUtils.isEmpty(viewModel.qu.value)) {
            val qus = viewModel.qu.value!!.split(" ")
            qus?.let {
                if (qus.size >= 1)
                    one = qus[0]
                if (qus.size >= 2)
                    two = qus[1]
                if (qus.size >= 3)
                    three = qus[2]
            }
        }
        dialog.showDialog(one, two, three)
        dialog.onDismis { one, two, three ->
            viewModel.qu.value = "${one.name} ${two.name} ${three.name}"
            viewModel.quIds.value = "${one.id} ${two.id} ${three.id}"
        }
    }
}